package org.tnc.budget.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.tnc.budget.model.AttachmentTable;
import org.tnc.budget.model.EventTable;

/**
 * 
 * @author houjj | 2011-4-4 下午04:03:06
 */
public class AttachmentTableDaoHibernate extends GenericHibernateDAO<AttachmentTable, Integer>{
	
	@SuppressWarnings("unchecked")
	public List<AttachmentTable> getAttachmentsByEventId(int eventId){
		List<AttachmentTable> list = new ArrayList<AttachmentTable>();
		
		EventTable eventTable = new EventTable();
		eventTable.setId(eventId);
		
		DetachedCriteria c = DetachedCriteria.forClass(AttachmentTable.class);
		c.add(Restrictions.eq("eventTable", eventTable));
		
		List<AttachmentTable> l = this.findByCriteria(c);
		if(l != null && l.size() > 0)
			list.addAll(l);
		
		return list;
		
	}
	
	public int deleteAttachByIds(Integer[] ids) {
		
		StringBuffer idArr = new StringBuffer();
		for (int i = 0; i < ids.length; i++) {
			idArr.append(ids[i]);
			if((i+1) < ids.length )
				idArr.append(",");
		}
		
		String sql = "DELETE attachment_table WHERE id IN ("+idArr.toString()+")";
		Session sess = this.getSession();
		try {
			SQLQuery q = sess.createSQLQuery(sql);
			int num = q.executeUpdate();
			
			return num;

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// sess.close();
		}
		
		return 0;
	}
	
	public int deleteAttachmentByEventId(int eventId){
		String sql = "DELETE attachment_table WHERE fk_event_id=?";
		Session sess = this.getSession();
		try {
			SQLQuery q = sess.createSQLQuery(sql);
			q.setParameter(0, eventId);
			
			int num = q.executeUpdate();
			
			return num;

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// sess.close();
		}
		
		return 0;
	}
}
